package com.mifengs.commonbase.base;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mifengs.commonbase.R;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.util.List;

import javax.inject.Inject;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by lihaoqi on 2017/10/30.
 */

public class BaseActivity<T extends BasePresenter> extends RxAppCompatActivity implements BaseView,EasyPermissions.PermissionCallbacks{

    private Dialog mLoadingDialog;
    public static final int REQUEST_PERMISSION_LOCATION = 1;
    public static final int REQUEST_PERMISSION_STORAGE = 2;
    public static final int REQUEST_PERMISSION_CAMERA = 3;
    public static final int REQUEST_PERMISSION_READ_WRITE_EXTERNAL_STORAGE = 4;

    @Inject
    protected T mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        doBeforeSetcontentView();
    }
    /**
     * 设置layout前配置
     */
    private void doBeforeSetcontentView() {
        initInjector();
        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    }
    //注入操作
    public void initInjector(){};


    @Override
    public void showShortToast(int resId) {
        ToastUitl.showShort(resId);
    }

    @Override
    public void showShortToast(String txt) {
        ToastUitl.showShort(txt);
    }

    @Override
    public void showLongToast(String txt) {
        ToastUitl.showLong(txt);
    }

    @Override
    public void showLongToast(int resId) {
        ToastUitl.showLong(resId);
    }

    @Override
    public void showLoading() {
        if(mLoadingDialog!=null){
            mLoadingDialog.show();
        }else{
            initProgressDialog();
        }
    }

    @Override
    public void hideLoading() {
        if(mLoadingDialog != null) {
            mLoadingDialog.cancel();
        }
    }

    @Override
    public void showNetError() {

    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 跳转结果至easyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 加载dialog 初始化
     */
    private void initProgressDialog(){
        View view = LayoutInflater.from(this).inflate(R.layout.common_dialog_loading, null);
        TextView loadingText = (TextView)view.findViewById(R.id.tv_loading_dialog_text);
        loadingText.setText("加载中...");
        mLoadingDialog = new Dialog(this, R.style.dialog);
        mLoadingDialog.setCancelable(true);
        mLoadingDialog.setCanceledOnTouchOutside(false);
        mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        mLoadingDialog.show();
    }

    protected void initNavigationBar(boolean isBackVisible, String title) {
        RelativeLayout llNavBar = (RelativeLayout) this.findViewById(R.id.navigation_bar);
        if (llNavBar != null) {
            LinearLayout llBack = (LinearLayout) this.findViewById(R.id.ll_back);
            llBack.setVisibility(isBackVisible ? View.VISIBLE : View.INVISIBLE);
            llBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
            TextView tvTitle = (TextView) this.findViewById(R.id.tv_title);
            tvTitle.setText(title);
        }
    }

    protected void isShowNavigationBar(boolean isShow){
        RelativeLayout llNavBar = (RelativeLayout) this.findViewById(R.id.navigation_bar);
        if (llNavBar != null) {
            if(isShow){
                llNavBar.setVisibility(View.VISIBLE);
            }else{
                llNavBar.setVisibility(View.GONE);
            }
        }
    }

    public void setStatusColorAndMode(int statusColor,boolean isLightMode){
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, statusColor));
        if(isLightMode){
            StatusBarUtils.StatusBarLightMode(this);
        }
    }

    public TextView getTextView(){
        TextView tvRigth = (TextView) this.findViewById(R.id.tv_right);
        return tvRigth;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
       // MobclickAgent.onPause(this);
    }

    public void showPermissionDeniedDialog(final Activity activity, String message){
        AlertDialog dialog = new AlertDialog.Builder(activity)
                .setMessage(message)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                                Uri.fromParts("package",activity.getPackageName(), null));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        activity.startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //                finish();
                    }
                }).create();
        dialog.show();
    }


    @AfterPermissionGranted(REQUEST_PERMISSION_LOCATION)
    public void needLoc() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            // mLocationClient.start();
            dingwei();
        } else {
            EasyPermissions.requestPermissions(this, "您需要定位权限",
                    REQUEST_PERMISSION_LOCATION, perms);
        }
    }


    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA)
    public void requestPermissionsCamera() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            toCamera();
        } else {
            EasyPermissions.requestPermissions(this, "app需要相机权限",
                    REQUEST_PERMISSION_CAMERA, perms);
        }
    }


    @AfterPermissionGranted(REQUEST_PERMISSION_READ_WRITE_EXTERNAL_STORAGE)
    public void readWritePermissions() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
//            ShareBoardConfig config = new ShareBoardConfig();
//            config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_NONE);
//            mShareAction.open(config);
//            if(isGoodsShare){
//                addTopView();
//            }
            afterHaveStorage();
        } else {
            EasyPermissions.requestPermissions(this, "您需要获取读写权限",
                    REQUEST_PERMISSION_READ_WRITE_EXTERNAL_STORAGE, perms);
        }
    }

    public void afterHaveStorage() {
    }

    public void toCamera() {
    }

    public void dingwei() {

    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if(requestCode == REQUEST_PERMISSION_LOCATION){
            showPermissionDeniedDialog(this,getString(R.string.setting_loaction_permission));
        }else if(requestCode == REQUEST_PERMISSION_CAMERA){
            showPermissionDeniedDialog(this,getString(R.string.setting_camera_permission));
        }else if(requestCode == REQUEST_PERMISSION_READ_WRITE_EXTERNAL_STORAGE){
            showPermissionDeniedDialog(this,getString(R.string.setting_storge_permission));
        }
    }
}
